package com.xsq.wifi.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.xsq.wifi.R;
import com.xsq.wifi.adapter.WifiListAdapter;
import com.xsq.wifi.callback.Callbacks;
import com.xsq.wifi.databinding.ActivityMainBinding;
import com.xsq.wifi.databinding.ActivityWifiListBinding;
import com.xsq.wifi.model.WifiListModel;
import com.xsq.wifi.utils.ProgressDialogUtil;
import com.xsq.wifi.utils.ToastUtil;
import com.xsq.wifi.utils.WifiListFetcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 编写人：李振德
 * 创建时间：2025/5/9
 */
public class WifiListActivity extends BaseActivity {

    private static final String TAG = "WifiListActivity";
    private ActivityWifiListBinding binding;
    private WifiListAdapter adapter;
    private List<WifiListModel> wifiListModels = new ArrayList<>();
    private PopupWindow popupWindow;
    private String deviceIp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityWifiListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        deviceIp = getIntent().getStringExtra("device_ip");
        initViews();
        binding.backImg.setOnClickListener(v -> {
            finish();
        });
    }

    private void initViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(WifiListActivity.this);
        binding.recyclerView.setLayoutManager(layoutManager);
        // 2. 从Intent获取传递过来的列表数据
        List<WifiListModel> receivedList = (List<WifiListModel>) getIntent().getSerializableExtra("wifi_list");
        wifiListModels.clear(); // 先清空原有数据
        wifiListModels.addAll(receivedList); // 添加接收到的数据
        adapter = new WifiListAdapter(wifiListModels,WifiListActivity.this);
        //详情
        adapter.setOnItemClickListener(new WifiListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String bssid) {
                showpopwindowwifi(bssid);
            }
        });
        binding.recyclerView.setAdapter(adapter);
    }

    public void showpopwindowwifi(String bssid){
        View chooseHeadView = LayoutInflater.from(WifiListActivity.this).inflate(R.layout.set_password_pop, null);
        popupWindow = new PopupWindow(chooseHeadView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        TextView bssidname = (TextView) chooseHeadView.findViewById(R.id.bssidname);
        bssidname.setText(bssid);
        EditText bssidpassword = (EditText) chooseHeadView.findViewById(R.id.bssidpassword);
        Button submit_button = (Button) chooseHeadView.findViewById(R.id.submit_button);
        Button cancel_button = (Button) chooseHeadView.findViewById(R.id.cancel_button);
        submit_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialogUtil.showProgressDialogText(WifiListActivity.this,"配网中...");
                WifiListFetcher.configureWifi(deviceIp, bssid, bssidpassword.getText().toString(), new Callbacks.ConfigCallback() {
                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ProgressDialogUtil.dismiss();
                                popupWindow.dismiss();
                                ToastUtil.show(WifiListActivity.this,"配网成功");
                            }
                        });
                        finish();
                    }

                    @Override
                    public void onFailure(String errorMsg) {
                        Log.v(TAG,errorMsg);
                        ProgressDialogUtil.dismiss();
                    }
                });
            }
        });
        cancel_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        setBackgroundAlpha(0.6f,popupWindow);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(chooseHeadView, Gravity.CENTER,0,0);
    }

    private void setBackgroundAlpha(float bgAlpha,PopupWindow popupWindowzi) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;//设置透明度（这是窗体本身的透明度，非背景）
        lp.dimAmount = bgAlpha;//设置灰度
        if (bgAlpha == 1) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为 红米米手机上半透明效果无效的bug
        }
        getWindow().setAttributes(lp);
        //监听弹窗
        popupWindowzi.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //弹窗关闭  dismiss()时恢复原样
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onStop() {
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
